﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		EntityBaseSaveOrUpdateListener.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 //   File:            EntityBaseSaveOrUpdateListener.cs
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using Dexter.Domain.Model;
using NHibernate.Event;

namespace Dexter.Repository.NHibernate.Listeners {

	/// <summary>
	/// 	NHibernate lister for set the update date and creation date when record is stored in the repository
	/// </summary>
	internal class EntityBaseSaveOrUpdateListener : BaseEntityPersisterListener {
		/// <summary>
		/// Called when [pre insert].
		/// </summary>
		/// <param name="event">The @event.</param>
		/// <returns></returns>
		public override bool OnPreInsert ( PreInsertEvent @event ) {
			if ( !( @event.Entity is EntityBase ) ) {
				return false;
			}

			var entityBase = ( ( EntityBase ) @event.Entity );

			entityBase.CreationDate = DateTime.Now;

			Set ( @event.Persister , @event.State , "CreationDate" , entityBase.CreationDate );

			entityBase.UpdateDate = DateTime.Now;

			Set ( @event.Persister , @event.State , "UpdateDate" , entityBase.UpdateDate );

			return false;
		}

		/// <summary>
		/// Called when [pre update].
		/// </summary>
		/// <param name="event">The @event.</param>
		/// <returns></returns>
		public override bool OnPreUpdate ( PreUpdateEvent @event ) {
			if ( !( @event.Entity is EntityBase ) ) {
				return false;
			}

			var entityBase = ( ( EntityBase ) @event.Entity );

			entityBase.UpdateDate = DateTime.Now;

			Set ( @event.Persister , @event.State , "UpdateDate" , entityBase.UpdateDate );

			return false;
		}
	}
}
